﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data;
using CommonLib.BLL;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using Aspose.Cells;

public partial class CRM_Store_ERP_SalePayEdit : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string objid = ViewState_ObjID = string.IsNullOrEmpty(Request.QueryString["ObjId"]) ? "Add" : Request.QueryString["ObjId"];
            ShowEditInfo(objid);
            StoreBind();
        }
    }

    private void StoreBind()
    {
        DataTable dtc = CRMMis.BLL.ERP_Customer.GetList("1=1").Tables[0];
        Store_CustomId.DataSource = dtc;
        Store_CustomId.DataBind();
        DataTable dt = SYS_USER.GetList("IS_MANAGER=1").Tables[0];
        Store_USER.DataSource = dt;
        Store_USER.DataBind();
        System.DateTime currentTime = new System.DateTime();
        currentTime = System.DateTime.Now;
        extcomb_year.SelectedItem.Value = currentTime.Year.ToString();
        extcomb_month.SelectedItem.Value = currentTime.Month.ToString();
    }

    private void ShowEditInfo(string objid)
    {
        if (objid == "Add")
        {
            exttxtf_Inuser_Name.Text = BS_LoginUserName;
            exthidn_InUser.Text = BS_LoginUserID;
            exttxtf_InDate.Text = DateTime.Now.ToDateTimeString();
        }
        else
        {
            var planDataTable = CRMMis.BLL.ERP_SalePay.GetList("PayId=" + objid).Tables[0];
            if (planDataTable.Rows.Count > 0)
            {
                DataRow row = planDataTable.Rows[0];
                int planState = Convert.ToInt32(row["state"]);
                //根据状态控制
                if (planState != 1)
                    extBtn_CheckInfo.Hidden = true;
                if (planState > 0)
                {
                    extBtn_SubmitInfo.Hidden = true;
                    extBtn_Save.Hidden = true;
                    SetContainerReadOnly(formPanel, true);
                    gridPanel_listdata.ColumnModel.Columns[1].Editable =                //商品名称
                        gridPanel_listdata.ColumnModel.Columns[6].Editable = false;     //数量
                }
                if (planState > 1)
                {
                    extBtn_CheckInfo.Hidden = true;
                }
            }
            SetContainer(formPanel, planDataTable);


            var planDetail = CRMMis.BLL.ERP_SalePay_Detail.GetList(" PayId=" + objid).Tables[0];
            Store1.DataSource = planDetail;
            Store1.DataBind();
            ViewState["Source"] = planDetail;
        }
    }


    ///<summary>
    /// 上传Excel
    ///</summary>
    [DirectMethod]
    public void ImportExcel()
    {
        if (extFuf_ImportExcel.HasFile)
        {
            string strExt = string.Empty;
            string strName = "";
            string strPathName = "";
            string sSize = "";

            if (extFuf_ImportExcel.PostedFile != null && extFuf_ImportExcel.PostedFile.ContentLength > 0)
            {
                strName = extFuf_ImportExcel.PostedFile.FileName;
                sSize = extFuf_ImportExcel.PostedFile.ContentLength.ToString();
                strExt = System.IO.Path.GetExtension(strName);
                strPathName = Guid.NewGuid().ToString() + strExt;
                if (strExt.ToUpper() != ".XLS" && strExt.ToUpper() != ".XLSX")
                {
                    X.Msg.Alert("提示", "Excel格式应为.xls，xls", MessageBox.Icon.WARNING).Show();
                    return;
                }
            }

            string strMapPath = Server.MapPath("../TmpFile/");
            string strPath = strMapPath + strPathName;
            extFuf_ImportExcel.PostedFile.SaveAs(strPath);
            OpenExcel(strPath);
        }
        else
        {
            X.Msg.Alert("提示", "请选择Excel", MessageBox.Icon.NONE).Show();
        }
    }


    private void OpenExcel(string filePath)
    {
        DataTable dt = new DataTable();
        if (filePath == "")
        {
            X.Msg.Alert("系统提示", "请选择要导入的Excel").Show();
            return;
        }
        Crack();//运行破解代码
        Workbook workbook = new Workbook(filePath);
        foreach (Worksheet sheet in workbook.Worksheets)
        {
            Cells cells = sheet.Cells;
            dt = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true);
            dt.TableName = sheet.Name;
        }
        DataTable dt1 = CommonLib.BLL.BS_DATASET_SQL.SqlGetTable("select * from V_CargoRelation where CustomerId ='"+extcomb_Customer.SelectedItem.Value+"'");
        DataTable dtv = DemoToTable(dt, dt1);
        Store1.DataSource = dtv;
        Store1.DataBind();
        string Sum = dtv.Compute("sum(SumPrice)", "true").ToString();
        extnumf_SumMoney.Text = Sum;
        ViewState["Source"] = dtv;
    }

    public DataTable DemoToTable(DataTable dt1, DataTable dt2)
    {
        var Test = from a in dt1.AsEnumerable()
                   join b in dt2.AsEnumerable()
                   on a.Field<string>("客户关键码") equals b.Field<string>("Sos_No")
                    into temp
                   from t in temp.DefaultIfEmpty()
                   select
                   new {
                       CusCargoName = a.Field<string>("商品名称"),
                       CusSpec = a.Field<string>("规格"),
                       CusVersion = a.Field<string>("型号"),
                       CusArea = a.Field<string>("产地"),
                       CusProduceName = a.Field<string>("生产厂家"),
                       BatchNo = a.Field<string>("批号"),
                       Sos_No = a.Field<string>("客户关键码"),
                       CargoName = t["CargoName"],
                       Spec = t["Spec"],
                       Version = t["Version"],
                       Area = t["Area"] ,
                       ProduceName = t["ProduceName"],
                       Supplyprice = t["CusSupplyprice"],
                       Count =  a.Field<string>("数量"),
                       SumPrice = int.Parse(a.Field<string>("数量"))*decimal.Parse(t["CusSupplyprice"].ToString())
                        };
        DataTable dtc = LLINQToDataTableT(Test);
        return dtc;
    }

    /// <summary>
    /// 保存，
    /// </summary>
    /// <param name="jsonData"></param>
    /// <param name="type">0,保存;1,提交;2,审核</param>
    [DirectMethod]
    public void SaveData(int type)
    {
        List<CRMMis.Model.ERP_SalePay_Detail> details = new List<CRMMis.Model.ERP_SalePay_Detail>();
        DataTable dtDetail = (DataTable)ViewState["Source"];
        CRMMis.Model.ERP_SalePay salepayModel;
        if (ViewState_ObjID == "Add")
        {
            salepayModel = new CRMMis.Model.ERP_SalePay();
            salepayModel.PayId = CRMMis.BLL.ERP_SalePay.GetNewID();
            salepayModel.PayNo = GetBusinessNo("JS", "ERP_SalePayJS", Convert.ToInt32(extcomb_Customer.SelectedItem.Value).ToString("000"));
            salepayModel.Inuser = BS_LoginUserID;
            salepayModel.Indate = exttxtf_InDate.Text.Trim();
            salepayModel.Customer = int.Parse(extcomb_Customer.SelectedItem.Value);
            salepayModel.Saler = extcomb_Saler.SelectedItem.Value;
            salepayModel.year = int.Parse(extcomb_year.SelectedItem.Value);
            salepayModel.month = int.Parse(extcomb_month.SelectedItem.Value);
            salepayModel.SumMoney = decimal.Parse(extnumf_SumMoney.Text.Trim().ToString());
            salepayModel.state = 0;
            if (type == 1)
                salepayModel.state = 1;    //提交
        }
        else
        {
            salepayModel = CRMMis.BLL.ERP_SalePay.GetModel(Convert.ToInt32(ViewState_ObjID));
            if (type == 1)
            {
                if (salepayModel.state == 0)
                    salepayModel.state = 1;    //提交
                else
                {
                    X.Msg.Alert("系统提示", "提交失败！当前记录已经提交").Show();
                    return;
                }
            }
            else if (type == 2)
            {
                if (salepayModel.state == 1)
                    salepayModel.state = 2;    //审核
                else
                {
                    X.Msg.Alert("系统提示", "审核失败！当前记录已经审核").Show();
                    return;
                }
            }

        }
        if (type < 2)
        {
            salepayModel.Remark = exttxtf_Remark.Text.Trim();
        }
        CommonLib.BLL.MyTransaction myTrans = new CommonLib.BLL.MyTransaction();
        myTrans.BeginTransaction();
        try
        {
            if (ViewState_ObjID == "Add")
            {
                CRMMis.BLL.ERP_SalePay.Add(myTrans, salepayModel);
            }
            else
            {
                CRMMis.BLL.ERP_SalePay.Update(myTrans, salepayModel);
                //删除子表
                if (type <= 2)
                    CRMMis.BLL.ERP_SalePay_Detail.DeleteFK(myTrans, "PayId = " + salepayModel.PayId);
            }
            if (type < 2)
            {
                foreach (DataRow dr  in dtDetail.Rows)
                {
                    CRMMis.Model.ERP_SalePay_Detail detailModel = new CRMMis.Model.ERP_SalePay_Detail();
                    detailModel.DetailId = CRMMis.BLL.ERP_SalePay_Detail.GetNewID();
                    detailModel.PayId = salepayModel.PayId;
                    detailModel.BatchNo = dr["BatchNo"].ToString();
                    detailModel.CusCargoName = dr["CusCargoName"].ToString();
                    detailModel.CusSpec = dr["CusSpec"].ToString();
                    detailModel.CusVersion = dr["CusVersion"].ToString();
                    detailModel.CusArea = dr["CusArea"].ToString();
                    detailModel.CusProduceName = dr["CusProduceName"].ToString();
                    detailModel.Sos_No = dr["Sos_No"].ToString();
                    detailModel.Count = int.Parse(dr["Count"].ToString());
                    CRMMis.BLL.ERP_SalePay_Detail.Add(myTrans, detailModel);
                    //details.Add(detailModel);
                }
            }
            if (type == 2)
            {
                foreach (DataRow dr in dtDetail.Rows)
                {
                    CRMMis.Model.ERP_SalePay_Detail detailModel = new CRMMis.Model.ERP_SalePay_Detail();
                    detailModel.DetailId = CRMMis.BLL.ERP_SalePay_Detail.GetNewID();
                    detailModel.PayId = salepayModel.PayId;
                    detailModel.BatchNo = dr["BatchNo"].ToString();
                    detailModel.CusCargoName = dr["CusCargoName"].ToString();
                    detailModel.CusSpec = dr["CusSpec"].ToString();
                    detailModel.CusVersion = dr["CusVersion"].ToString();
                    detailModel.CusArea = dr["CusArea"].ToString();
                    detailModel.CusProduceName = dr["CusProduceName"].ToString();
                    detailModel.Sos_No = dr["Sos_No"].ToString();
                    detailModel.Count = int.Parse(dr["Count"].ToString());
                    CRMMis.BLL.ERP_SalePay_Detail.Add(myTrans, detailModel);
                }
            }
            myTrans.CommitTran();
            ViewState_ObjID = salepayModel.PayId.ToString();
            exttxtf_PayNo.Text = salepayModel.PayNo.ToString();
            string handler = "";
            if (type > 0)
                handler = "closeCurrTab();";
            X.Msg.Alert("系统提示", "保存成功！", handler).Show();
        }
        catch (Exception ex)
        {
            myTrans.RollBackTran();
            X.Msg.Alert("系统提示", "保存失败！</br>" + ex.Message).Show();
        }
    }

}